<?php
declare(strict_types=1);

namespace App\Console\Commands\Tasks;


use App\Exceptions\BasicException;
use App\Repositories\BlindBox\ExchangeRepository;
use Illuminate\Console\Command;

class ScriptFixBlindBoxExchangeCommand extends Command
{

    protected $signature = 'script:blindBoxExchange {user_id}';
    protected $description = '修复盲盒礼物兑换';

    public function __construct()
    {
        parent::__construct();
    }


    public function handle()
    {
        $userIdStr = $this->argument("user_id");
        if (empty($userIdStr)) {
            throw new BasicException(-1, '缺少用户ID');
        }
        $userIds = explode(",", $userIdStr);
        if (empty($userIds)) {
            throw new BasicException(-1, '参数异常');
        }

        foreach($userIds as $userId) {
            $recordList             = app("model_blind_box_draw_record")->select('pool_id', 'prize_id', 'created_at')->where('accept_user_id', $userId)->get();
            $exchangeList           = app("model_blind_box_exchange_record")->selectRaw(' max(created_at) as created_at, pool_id')->where('user_id', $userId)->groupBy('pool_id')->get();
            $exchangeListWithPoolId = $exchangeList->keyBy('pool_id');

            foreach ($recordList as $record) {
                if ($record->created_at >$exchangeListWithPoolId[$record->pool_id]['created_at']) {
                    app('redis')->hset(ExchangeRepository::userIllustrateCacheKey . "_" . $userId . "_" . $record->pool_id, $record->prize_id, 1);
                    app('redis')->expire(ExchangeRepository::userIllustrateCacheKey . "_" . $userId . "_" . $record->pool_id, 30 * 24 * 3600);
                }
            }
        }
    }
}